package com.example.zx.theline.sgjh.pub;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zx.theline.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.CheckPersonBean;
import GsonBean.SuccessBean;
import GsonBean.post.CheckPersonPost;
import Utils.MyToast;
import Utils.RefreshManager;
import app.MyApplication;
import automatchingview.AutoMatchingPopuWindow;
import base.BaseActivity;
import greendao.UserDao;
import greendao.entity.User;
import network.NetWorkApi;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.AutoMatchingPopuClickListener;
import views.ZdjhrView;

import static Utils.MyToast.showFail;

public class EditorGuardianActivity extends BaseActivity implements View.OnClickListener {

    //监督计划表编号
    public static String jdjhbBh;
    //是否有编辑监护人权限
    public static boolean add_power=true;


    private TextView jhh;
    private TextView queding;
    private TextView quxiao;
    private TextView add;
    private LinearLayout bjjhr;
    private FrameLayout frameLayout;

    private CheckPersonBean mCheckPersonBean;
    private List<CheckPersonBean.RowsBean> checkList = new ArrayList<>();

    private PopupWindow mPopu;
    private AutoMatchingPopuWindow window;

    private UserDao mUserDao;
    List<User> mSourceList;
    //已经有的计划监护人
    List<User> mCheckList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor_guardian);
        InitView();
        InitData();
        InitListen();
    }

    @Override
    protected void InitView() {
        queding = (TextView) findViewById(R.id.queding);
        quxiao = (TextView) findViewById(R.id.quxiao);
        bjjhr = (LinearLayout) findViewById(R.id.bjjhr);
        add = (TextView) findViewById(R.id.add);
        jhh = (TextView) findViewById(R.id.jhh);
        frameLayout = (FrameLayout) findViewById(R.id.framelayout);
        if(add_power){
            add.setVisibility(View.VISIBLE);
            queding.setVisibility(View.VISIBLE);

        } else {
            add.setVisibility(View.GONE);
            queding.setVisibility(View.GONE);
        }
    }

    @Override
    protected void InitData() {

        MyApplication.ShowWaitDialog(this);

        Map<String, String> map = new HashMap<>();
        map.put("jdjhbBh", jdjhbBh);
        map.put("lrdwId", MyApplication.getmLoginUser().getUserUnitId());
        NetWorkApi.getSgjhry(map, new Callback<CheckPersonBean>() {
                    @Override
                    public void onResponse(Call<CheckPersonBean> call, Response<CheckPersonBean> response) {
                        try {
                            mCheckPersonBean = response.body();
                            if (checkList.size() > 0) {
                                checkList.clear();
                            }
                            checkList.addAll(mCheckPersonBean.getRows());
                            if (mCheckPersonBean.getMsg().equals("success")) {
                                bjjhr.removeAllViews();
                                jhh.setText(jdjhbBh);
                                if (checkList.size() != 0) {
                                    AddJianhrInfo(checkList);
                                }
                            }
                            //初始化选中人
                            InitCheckPerson();
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<CheckPersonBean> call, Throwable t) {
                        showFail();
                    }
                }

        );
    }

    @Override
    protected void InitListen() {
        quxiao.setOnClickListener(this);
        queding.setOnClickListener(this);
        add.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.queding: //指定监护人点击确定按钮
                if(mCheckList.size()==0){
                    Toast.makeText(EditorGuardianActivity.this, "请选择一个监护人", Toast.LENGTH_SHORT).show();
                }
                postNewJianhrList();
                //清楚数据库缓存 避免数据库缓存影响 下一次选择监护人
                MyApplication.getDaoSession().clear();
                break;
            case R.id.quxiao:
                //清楚数据库缓存 避免数据库缓存影响 下一次选择监护人
                MyApplication.getDaoSession().clear();
                finish();
                break;
            case R.id.add:
                showAddPopu();
                break;
        }
    }


    //  向dialog中添加计划中已经存在的监护人信息
    public void AddJianhrInfo(List<CheckPersonBean.RowsBean> mList) {
        for (int i = 0; i < mList.size(); i++) {
            ZdjhrView zdjhrView = new ZdjhrView(this, false);
            zdjhrView.cancelOnclick();
            zdjhrView.setJhrxm(mList.get(i).getLrdwmc()+"  "+ mList.get(i).getJhrname());
            zdjhrView.setJhrdh(mList.get(i).getJhrphone());
            bjjhr.addView(zdjhrView, i);
        }
    }

    //增加popu中选中的整改人
    public void addPerson(List<User> list) {
        for (int i = 0; i < list.size(); i++) {
            ZdjhrView zdjhrView = new ZdjhrView(this, false);
            zdjhrView.cancelOnclick();
            zdjhrView.setJhrxm(list.get(i).getLjyyxWorkerName());
            zdjhrView.setJhrdh(list.get(i).getLjyyxWorkerTel());
            bjjhr.addView(zdjhrView, i);
        }
    }

    //删除已经有的监护人，新增从pou中选中的整改人
    public void deletePerson() {
        bjjhr.removeAllViews();
    }


    //初始化选中人
    private void InitCheckPerson() {
        mUserDao = MyApplication.getDaoSession().getUserDao();
        try {
            mSourceList = mUserDao.queryBuilder()
                    .where(UserDao.Properties.LjyyxDwxxId.eq(MyApplication.getmLoginUser().getUserUnitId()))
                    .list();
        } catch (Exception e){
            Toast.makeText(this,"本地无本单位用户信息，请前往用户中心更新字典表。",Toast.LENGTH_SHORT).show();
        }
        final List<String> l = new ArrayList<>();
        for (CheckPersonBean.RowsBean rows : checkList) {
            l.add(rows.getJhrname());
        }
        mCheckList = mUserDao.queryBuilder().where(UserDao.Properties.LjyyxWorkerName.in(l)).list();
        for (User item : mCheckList) {
            item.setChecked(true);
        }
    }

    private void showAddPopu() {

        if (mPopu == null) {
            window = new AutoMatchingPopuWindow();
            window.Builder(this)
                    .setOutsideTouchable(false)
                    .setCheckedList(mCheckList)
                    .setSourceList(mSourceList)
                    .setEditTextWatcher(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            if (s.length() == 0) {
                                window.UpListViewAdapter(mSourceList);
                            } else {
                                window.UpListViewAdapter(mUserDao.queryBuilder()
                                        .where(UserDao.Properties.LjyyxWorkerName.like("%" + s.toString() + "%"))
                                        .list());
                            }
                        }
                    })
                    .setAutoMatchingPopuClickListener(new AutoMatchingPopuClickListener<User>() {
                        @Override
                        public void OnAutoMatchingPopClicked(List<User> list) {
                            if (list.size() == 0) {
                                deletePerson();
                                mCheckList = list;
                            } else {
                                deletePerson();
                                addPerson(list);
                                mCheckList = list;
                            }
                            mPopu.dismiss();
                        }
                    });
            mPopu = window.CreatePopu();
        }
        mPopu.showAtLocation(frameLayout, Gravity.RIGHT, 0, 0);
    }

    //指定监护人点击确定按钮 将监护人信息上传到服务器
    private void postNewJianhrList() {
        final List<CheckPersonPost> checkPersonPostlist = new ArrayList<>();
        //取所有的编辑行的内容添加到集合中
        for (int i = 0; i < bjjhr.getChildCount(); i++) {
            ZdjhrView mView = (ZdjhrView) bjjhr.getChildAt(i);
            if (!mView.auto_fzr.getText().toString().equals("")) {
                CheckPersonPost mRowsBean = new CheckPersonPost();
                mRowsBean.setJdjhbBh(jhh.getText().toString());
                mRowsBean.setJhrname(mView.auto_fzr.getText().toString());
                mRowsBean.setJhrphone(mView.et_dh.getText().toString());
                mRowsBean.setLrrId(MyApplication.getmLoginUser().getUserDisplayName());
                mRowsBean.setLrdwId(MyApplication.getmLoginUser().getUserUnitId());
                mRowsBean.setLrdwmc(MyApplication.getmLoginUser().getUserUnitName());
                checkPersonPostlist.add(mRowsBean);
            }
        }
        if (checkPersonPostlist.size() > 0) { //将新集合上传到服务端
            MyApplication.ShowWaitDialog(this);
            NetWorkApi.saveEditerPerson(checkPersonPostlist, new Callback<SuccessBean>() {
                        @Override
                        public void onResponse(Call<SuccessBean> call, Response<SuccessBean> response) {
                            try {
                                SuccessBean mSuccessBean = response.body();
                                if (mSuccessBean.getCount() != 0) {
                                    MyToast.showToast("修改成功");
                                    RefreshManager.Jdjc.RefreshSgjhryap();
                                    finish();
                                    //刷新施工监护人员安排界面
                                    RefreshManager.Jdjc.RefreshSgjhryap();
                                } else {
                                    MyToast.showToast("修改失败");
                                }
                            } catch (Exception e) {
                                MyToast.showFail();
                            }
                            MyApplication.HideWaitDialog();
                        }

                        @Override
                        public void onFailure(Call<SuccessBean> call, Throwable t) {
                            MyToast.showFail();
                        }
                    }

            );
        }
    }

}
